package dichotomyMethod;

import org.junit.Test;

import java.util.Arrays;

/*
 *@description 搜索旋转排序数组
 *@author hkfan
 *@version 1.0
 *@create 2025/5/15 15:33
*/
public class LeetCode_33 {

    @Test
    public void test(){
        System.out.println(
                search(new int[]{4,5,6,7,0,1,2},0)
        );

    }

    public int search(int[] nums, int target) {
        //1. 定义变量
        int left = 0,right = nums.length-1;
        //2. 重写二分规则
        while (left<right){
            //2.1 特殊情况返回
            int mid = (left+right)/2;
            if (nums[mid]==target){
                return mid;
            } else if (nums[left]==target) {
                return left;
            } else if (nums[right]==target) {
                return right;
            }
            //2.2 分类讨论
            if (target>nums[left]){ //右半部分
                if (nums[mid]<target && nums[mid]>nums[left]){
                    left=mid+1;
                } else {
                    right=mid-1;
                }
            }else {
                if (nums[mid]>target && nums[mid]<nums[left]){
                    right=mid-1;
                }else {
                    left=mid+1;
                }
            }

        }
        if (nums[left]==target){
            return left;
        }
        return  -1;
    }


}
